﻿// //文档就绪函数
$(function () {
    show();
})
var totalCount = 0;
var pageIndex = 1;
var pageSize = 100;

//采购状态下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "/Purchase/GetProcurementState",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(data, function (index, item) {
                options += '<option value="' + item.value + '">' + item.text + '</option>';
            });
            $("#procurementState").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
            // 可以考虑显示一个错误消息给用户
        }
    });
});
//采购显示
function show() {
    layui.use('table', function () {
        // var form = layui.form;
        var table = layui.table;
        //查询
        var procurementNo = $("#procurementNo").val();
        var productNo = $("#productNo").val();
        var productName = $("#productName").val();
        var procurementState = $("#procurementState").val();
        $.ajax({
            url: "/Purchase/GetProcurementShow",
            type: "get",
            data: {
                procurementNo: procurementNo,
                productNo: productNo,
                productName: productName,
                procurementState: procurementState,
                pageIndex: pageIndex,
                pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res);
                if (res.code === 0) {
                    console.log(res.data.list)
                    table.render({
                        elem: procurementData,//对应HTML中表格的id
                        data: res.data.list,//绑定获取的数据
                        toolbar: '#toolbarDemo',//导出
                        defaultToolbar: ['exports'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'procurementNo', title: '订单号', width: 140 },
                            { field: 'productName', title: '产品名称', width: 150 },
                            { field: 'productNo', title: '产品编号', width: 110 },
                            { field: 'productSpec', title: '规格', width: 110 },
                            { field: 'unitName', title: '单位', width: 110 },
                            { field: 'buyProductsNum', title: '数量', width: 110 },
                            { field: 'buyProductsTotal', title: '总额', width: 120 },
                            { field: 'vendorNo', title: '供应商编号', width: 110 },
                            { field: 'vendorName', title: '供应商名称', width: 110 },
                            {
                                field: 'productsTotal', title: '订单总额', templet: function (d) {
                                    return (d.returnsNum + d.buyProductsNum) * d.price;
                                }, width: 170
                            },
                            { field: 'procurementStateText', title: '状态', width: 120 },
                            {
                                field: 'isRecorded', title: '是否入账', width: 100, templet: function (d) {
                                    if (d.isRecorded === false) {
                                        return '<span>否</span>';
                                    } else if (d.isRecorded === true) {
                                        return '<span>是</span>';
                                    } else {
                                        return " ";
                                    }
                                }
                            },
                            {
                                field: 'isReturn', title: '退货', width: 100, templet: function (d) {
                                    if (d.isReturn === false) {
                                        return " ";
                                    } else if (d.isReturn === true) {
                                        return '<span>退</span>';
                                    } else {
                                        return " ";
                                    }
                                }
                            },
                            {
                                field: 'createTime', title: '创建时间', templet: function (d) {
                                    return formatTime(d.createTime);
                                }, width: 170
                            },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="procurementmodel(' + d.procurementId + ')"><i class="layui-icon layui-icon-search"></i>查看</a> ' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="procurementStorage(' + d.procurementId + ')"><i class="layui-icon layui-icon-edit"></i>入库</a>' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.buyProductsId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="returnsmodel(' + d.procurementId + ')"><i class="layui-icon layui-icon-edit"></i>退货</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="Recordedmodel(' + d.procurementId + ')"><i class="layui-icon layui-icon-edit"></i>入账</a>';
                                }
                            }
                        ]],
                        page: true, // 是否显示分页
                        count: totalCount,
                        limits: [6, 9, 14],
                        limit: 6,// 每页默认显示的数量
                        curr: pageIndex,
                    })
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    });
    // 查看详情
    window.procurementmodel = function (procurementId) {
        // 先根据id获取要编辑的数据，发起Ajax请求
        $.ajax({
            type: "get",
            url: "/Purchase/GetFanProcurement",  // 替换为实际的后台根据id获取数据的接口地址
            data: {
                procurementId: procurementId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                try {
                    const { data } = JSON.parse(res);
                    //console.log(data)
                    if (data) {
                        const { buyProductsData } = data;
                        var procurement = data;
                        console.log(procurement);
                        console.log(buyProductsData);
                        // 反填表单的函数
                        fillForm(procurement);
                        $('#procurementStateText').val(buyProductsData[0].procurementStateText);
                        //渲染表格的函数
                        //renderTable(buyProductsData);
                        layui.use('table', function () {
                            var table = layui.table;
                            if (buyProductsData) {
                                var inst = table.render({
                                    elem: '#procurementProduct', // 对应HTML中表格的id
                                    data: buyProductsData, // 绑定获取的数据
                                    cols: [[
                                        { field: 'productNo', title: '产品编码' },
                                        { field: 'productName', title: '产品名称' },
                                        { field: 'productSpec', title: '规格' },
                                        { field: 'unitName', title: '单位' },
                                        { field: 'buyProductsNum', title: '数量' },
                                        { field: 'batch', title: '批次' },
                                        { field: 'buyProductsNum', title: '入库数' },
                                        { field: 'buyProductsNum', title: '库位' },
                                        { field: 'price', title: '单价' },
                                        { field: 'buyProductsTotal', title: '总额' },
                                    ]],
                                });
                            }
                        });
                        resolve(procurement, buyProductsData);
                    } else {
                        layui.layer.msg(res.message, { icon: 2 });
                        reject(res.message);
                    }
                } catch (e) {
                    //console.error(e);
                    //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                    //reject('数据解析失败');
                }
            },
        });

        layer.open({
            type: 1,
            title: '采购单详情',
            content: `
                      <form class="layui-form" action="/CreateWarehouse">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">采购单号</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementNos" id="procurementNos" lay-verify="required" autocomplete="off" placeholder="可不填写，自动生成" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据类型</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementTypeName" id="procurementTypeName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据状态</label>
            <div class="layui-input-inline">
                <input type="text" id="procurementStateText" name="procurementStateText" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">关联单号</label>
            <div class="layui-input-inline">
                <input type="text" id="associateNumber" name="associateNumber" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
            <input type="text" name="singleTime" id="singleTime" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">收货日期</label>
            <div class="layui-input-inline">
                <input type="text" name="harvestay" id="harvestay" autocomplete="off" class="layui-input" lay-verify="required" disabled>
            </div>
        </div>
    <div class="layui-inline">
            <label class="layui-form-label">供应商编号</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorNo" name="vendorNo" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorName" name="vendorName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">联系人</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPerson" id="procurementPerson" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPhone" id="procurementPhone" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementRemark" id="procurementRemark" autocomplete="off" class="layui-input" lay-verify="required" disabled>
            </div>
        </div>
    </div>
    
    <table class="layui-hide" id="procurementProduct" lay-filter="test"></table>
</form>

`,
            area: ['1400px', '800px'],
            success: function () {

                // 对弹层中的表单进行初始化渲染
                //form.render();
            }
        });
    };
    var obj = {
        procurementId: 0,
        clientName: '',
        procurementState: '',
        isRecorded: '',
        isReturn: '',
    };
    // 反填表单的函数
    function fillForm(procurement) {
        
        $('#procurementNos').val(procurement.procurementNo);
        $('#procurementTypeName').val(procurement.procurementTypeName);
        
        $('#associateNumber').val(procurement.associateNumber);
        $('#vendorNo').val(procurement.vendorNo);
        $('#vendorName').val(procurement.vendorName);
        $('#clientName').val(procurement.clientName);
        $('#procurementPerson').val(procurement.procurementPerson);
        $('#procurementPhone').val(procurement.procurementPhone);
        $('#procurementRemark').val(procurement.procurementRemark);
        $('#singleMaker').val(procurement.singleMaker);
        
        //const hourss = ("0" + dates.getHours()).slice(-2);
        //const minutess = ("0" + dates.getMinutes()).slice(-2);
        const date = new Date(procurement.singleTime);
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        $('#singleTime').val(year + "-" + month + "-" + day);
        const dates = new Date(procurement.harvestay);
        const years = date.getFullYear();
        const months = ("0" + (date.getMonth() + 1)).slice(-2);
        const days = ("0" + date.getDate()).slice(-2);
        $('#harvestay').val(years + "-" + months + "-" + days);
        obj.procurementId = procurement.procurementId
        obj.clientName = procurement.clientName
        obj.procurementState = procurement.procurementState
        obj.isRecorded = procurement.isRecorded
        obj.isReturn = procurement.isReturn
        console.log(obj)
        console.log(procurement)
        // 重新渲染表单元素（如果有）
        //form.render();
    }

    // 退货
    window.returnsmodel = function (procurementId) {
        // 先根据id获取要编辑的数据，发起Ajax请求
        $.ajax({
            type: "get",
            url: "/Purchase/GetFanProcurement",  // 替换为实际的后台根据id获取数据的接口地址
            data: {
                procurementId: procurementId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                try {
                    const { data } = JSON.parse(res);
                    //console.log(data)
                    if (data) {
                        const { buyProductsData } = data;
                        var procurement = data;
                        console.log(procurement);
                        console.log(buyProductsData);
                        // 反填表单的函数
                        fillForm(procurement);
                        $('#procurementStateText').val(buyProductsData[0].procurementStateText);

                        //渲染表格的函数
                        //renderTable(buyProductsData);
                        layui.use('table', function () {
                            var table = layui.table;
                            if (buyProductsData) {
                                var inst = table.render({
                                    elem: '#returnDetail', // 对应HTML中表格的id
                                    data: buyProductsData, // 绑定获取的数据
                                    cols: [[
                                        { type: 'checkbox', fixed: 'left' },
                                        { field: 'productNo', title: '产品编码' },
                                        { field: 'productName', title: '产品名称' },
                                        { field: 'productSpec', title: '规格' },
                                        { field: 'unitName', title: '单位' },
                                        { field: 'buyProductsNum', title: '数量' },
                                        { field: 'batch', title: '批次', edit: 'text' },
                                        { field: 'returnsNum', title: '退货数', edit: 'text' },
                                        { field: 'price', title: '单价' },
                                        { field: 'buyProductsTotal', title: '总额' },
                                    ]],
                                });
                            }
                        });
                        resolve(procurement, buyProductsData);
                    } else {
                        layui.layer.msg(res.message, { icon: 2 });
                        reject(res.message);
                    }
                } catch (e) {
                    //console.error(e);
                    //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                    //reject('数据解析失败');
                }
            },
        });

        layer.open({
            type: 1,
            title: '采购退货',
            content: `
                      <form class="layui-form" action="/CreateWarehouse">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">采购单号</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementNos" id="procurementNos" lay-verify="required" autocomplete="off" placeholder="可不填写，自动生成" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据类型</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementTypeName" id="procurementTypeName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据状态</label>
            <div class="layui-input-inline">
                <input type="text" id="procurementStateText" name="procurementStateText" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">关联单号</label>
            <div class="layui-input-inline">
                <input type="text" id="associateNumber" name="associateNumber" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
            <input type="text" name="singleTime" id="singleTime" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">收货日期</label>
            <div class="layui-input-inline">
                <input type="text" name="harvestay" id="harvestay" autocomplete="off" class="layui-input" lay-verify="required" disabled>
            </div>
        </div>
    <div class="layui-inline">
            <label class="layui-form-label">供应商编号</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorNo" name="vendorNo" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorName" name="vendorName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">联系人</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPerson" id="procurementPerson" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPhone" id="procurementPhone" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementRemark" id="procurementRemark" autocomplete="off" class="layui-input" lay-verify="required" disabled>
            </div>
        </div>
    </div>
    
    <table class="layui-hide" id="returnDetail" lay-filter="test"></table>
    <div class="layui-form-item" style="text-align:center;margin-top:50px">
        <button class="layui-btn" lay-submit lay-filter="demo-login">确认</button>
        <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Purchase/ProcurementShow'">取消</button>
    </div>
</form>

`,
            area: ['1400px', '800px'],
            success: function () {
                // 对弹层中的表单进行初始化渲染
                //form.render();
                
            }
        });
        
    };
    
}
//退货通过
layui.use(['layer', 'form', 'table'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;

     //退货通过
    form.on('submit(demo-login)', function (data) {
        var field = data.field;
        var checkStatus = table.checkStatus('returnDetail');
        field.returnData = checkStatus.data.map(function (item) {
            return item
        });
        console.log(field)
        var buyProductsId = field.returnData.map(x => x.buyProductsId)
        var returnsNum = field.returnData.map(x => x.returnsNum)
        console.log(field.returnData.map(x=>x.buyProductsId))
        console.log(field.returnData.map(x => x.returnsNum))
        var field = {
            buyProductsId: buyProductsId,
            returnsNum: returnsNum
        }
        $.ajax({
            url: '/Purchase/GetAddReturn',
            type: 'post',
            data: {
                field: field,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(field)
                console.log(res)
                if (res.code == 1) {
                    layer.alert(res.message);
                    setTimeout(function () {
                        location.reload();
                    }, 2000);
                } else if (res.code == -2) {
                    layer.alert(res.message);
                } 
                else {
                    layer.alert("操作失败");
                }
            }
        })
        return false; // 阻止默认 form 跳转
    });
});
 //定义删除数据的函数（此处简单示意，可参考之前详细的删除功能代码完善）
window.deleteData = function (buyProductsId) {
    console.log(buyProductsId)
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/Purchase/GetDelectProcurement",  // 替换为实际的后台删除数据接口地址
            data: {
                data: JSON.stringify({ buyProductsId: buyProductsId }),
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

// 点击批量删除按钮的事件处理
$('#batchDeleteBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取buyProductsId）
    var checkStatus = table.checkStatus('procurementData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.buyProductsId;
    });
    if (selectedData.length === 0) {
        layer.msg("请至少选择一条要删除的数据", { icon: 2 });
        return;
    }

    console.log(selectedData);
    layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
        var buyProductsIds = {
            buyProductsId: selectedData
        }
        // 发送批量删除请求到后端
        $.ajax({
            url: "/Purchase/GetPlDelectProcurement", // 后端处理批量删除的接口地址，需根据实际情况调整
            type: "post",
            data: {
                procurement: buyProductsIds,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res.code);
                if (res.code > 0) {
                    layer.msg("批量删除成功", { icon: 1 })
                    // 重新加载表格数据，展示更新后的列表
                    show();
                } else {
                    layer.msg("批量删除失败:" + res.message, { icon: 2 });
                }
            },
            error: function () {
                console.log("批量删除数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    })
})

//入账
window.Recordedmodel = function (buyProductsId) {
    console.log(buyProductsId)
    layer.confirm('确定要入账吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/Purchase/GetProcurementRecorded",  // 替换为实际的后台删除数据接口地址
            data: {
                buyProductsId: JSON.stringify({ buyProductsId: buyProductsId }),
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("入账成功");
                    show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("入账失败");

                }
            },
            error: function () {
                layer.msg('入账失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

// 点击编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取procurementId）
    var checkStatus = table.checkStatus('procurementData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.procurementId;
    });
    console.log(selectedData);
    if (selectedData.length === 0) {
        layer.msg("请选择一条要编辑的数据", { icon: 2 });
        return;
    }
    localStorage['procurementId'] = selectedData;
    location.href = '/Purchase/UpdProcurement';
});

//采购入库
window.procurementStorage = function (procurementId) {
    console.log(procurementId)
    localStorage['procurementId'] = procurementId;
    location.href = '/Purchase/ProcurementStorage';
};
// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear(); // 获取年份
        var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，+1是因为getMonth()返回的月份是从0开始计数的
        var day = ('0' + date.getDate()).slice(-2); // 获取日期
        var hour = ('0' + date.getHours()).slice(-2); // 获取小时
        var minute = ('0' + date.getMinutes()).slice(-2); // 获取分钟
        var second = ('0' + date.getSeconds()).slice(-2); // 获取秒
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}